package httpServer;

import java.io.IOException;
import java.net.ServerSocket;

/**
 * This class listens for connection to the server on port 8080
 * Once a connection has been established, the connection
 * is put on a separate thread and started
 * 
 * @author Scott Wendlandt, Li Weihan, and Rebecca Chandler
 *
 */
public class HTTPServer{

	/**
	 * Starts up the GUI and passes it to the server
	 * so updates to its display can be made
	 */
	public static void main(String [] ignored) {
		ServerUI ui = new ServerUI();
		new HTTPServer(ui);
	}

	public HTTPServer(ServerUI ui) {
		ServerSocket serverSocket = null;
		try {
			serverSocket = new ServerSocket(8080);
			while (true) {
				try {
					// When a client connects, open a socket for it and start it on a separate thread
					ServerClientConnection request = new ServerClientConnection(serverSocket.accept());
					Thread thread = new Thread(request);
					thread.start();
					// Update the UI to inform the user that a client has connected
					ui.addStatus("New client connected!");
				} catch (IOException e) {
					System.out.println("Error making a new connection");
				}
			}
		}catch (IOException e) {
			System.out.println("Error making the Server Socket");
		} finally {
			if (serverSocket != null) {
				try {
					serverSocket.close();
				} catch (IOException e) {
					System.out.println("Error when closing the server socket.");
				}
			}
		}
	}
}
